package com.example.jussi.httpurlconnectiongetdemo;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Base64;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 *  依赖 blog (Tomcat HttpServlet)
 */
public class MainActivity extends AppCompatActivity {
    TextView textView;
    EditText editText;
    String result;
    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg.what == 0x01){
                textView.append(result);
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        editText = (EditText) findViewById(R.id.editText);
        textView = (TextView) findViewById(R.id.textView);
        textView.setText("");
    }

    public void send(View source){
        result = "";
        new Thread(){
            @Override
            public void run() {
                super.run();
                String pathString = "http://192.168.1.106:8080/blog/dealGet.jsp?content=" + encodePath(editText.getText().toString());
                try {
                    URL url = new URL(pathString);
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    InputStream inputStream = connection.getInputStream();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"));
                    String string;
                    while( (string = reader.readLine()) != null){
                        result += string + "\n";
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                handler.sendEmptyMessage(0x01);
            }
        }.start();
    }

    private String encodePath(String path) {
        String  result = null;
        try {
            result = Base64.encodeToString(path.getBytes(), Base64.DEFAULT);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

}
